package cn.code.auth.authorize.security;

import cn.code.admin.dao.AuthTbRoleMapper;
import cn.code.admin.dao.AuthTbUserMapper;
import cn.code.admin.model.AuthTbRole;
import cn.code.admin.model.AuthTbUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by 汪玉东 on 2017/11/4.
 */
@Service
public class CustomUserService implements UserDetailsService { //自定义UserDetailsService 接口

    @Autowired
    AuthTbUserMapper userDao;

    @Autowired
    AuthTbRoleMapper authTbRoleMapper;

    @Override
    public UserDetails loadUserByUsername(String username) { //重写loadUserByUsername 方法获得 userdetails 类型用户
        AuthTbUser user=new AuthTbUser();
        user.setName(username);
        user = userDao.selectOne(user);
        if(user == null){
            throw new UsernameNotFoundException("用户名不存在");
        }
        List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
        //用于添加用户的权限。只要把用户权限添加到authorities 就万事大吉。
        List<AuthTbRole>  roles = authTbRoleMapper.getRoleAndPowerListByUserId(user.getId());
        for(AuthTbRole role:roles)
        {
            GrantedAuthority grantedAuthority=new MyGrantedAuthority(role.getId(),role.getName(),role.getAuthTbRolePower());
            authorities.add(grantedAuthority);
        }

        SecUser secUser=new SecUser();
        secUser.setUsername(user.getName());
        secUser.setId(user.getId());
        secUser.setPassword(user.getPassword());
        secUser.setGrantedAuthorities(authorities);
        return secUser;

    }
}
